package com.team.app.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.team.app.enums.ObjectType;
import com.team.app.enums.UrlFixed;
import com.team.app.model.Auth;
import com.team.app.model.AuthAcept;
import com.team.app.model.Role;
import com.team.app.service.AuthAceptService;
import com.team.app.service.AuthService;
import com.team.app.service.RoleService;
import com.team.app.service.VehicleService;
import com.team.app.util.ConvertUtil;
import com.team.app.util.FormatUtil;
import com.team.app.util.UpdateFileUtil;



/**
 * Handles requests for the application home page.
 */
@Controller
public class AuthController extends AbstractAuthCheck{

	private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

	@Autowired	
	private AuthService authService;
	
	@Autowired	
	private AuthAceptService authAceptService;
	
	@Autowired	
	private RoleService roleService;
	
	@Autowired	
	private VehicleService vehicleService;
	
	
	/**
	 * Simply selects the home view to render by returning its name.
	 * @throws IOException 
	 */
	@RequestMapping(value = "/auth", method = RequestMethod.GET)
	public String indexAction(Model model ,HttpSession s){	
		logger.info("AuthController index");
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");
		if(loginAuth != null){
			return "auth/index";
		}
		return "redirect:login";
	}
	
	@RequestMapping(value = "/auth/object-active", method = {RequestMethod.GET,RequestMethod.POST})
	public String objectActiveAction(Model model,HttpSession s) throws IOException {
		
		if(!checkView(s, "/auth/object-active")){
    		return accessDenied();
    	}
		
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");
		if(loginAuth.getObjectType().equals(ObjectType.TYPE_SERVICE.getKey())){
			model.addAttribute("urls",  UrlFixed.getUrls());
		}else{
			model.addAttribute("urls",  UrlFixed.getUrls(authAceptService.findByRole(loginAuth.getRoleId())));
		}
		
		return "auth/object-active";
	}
	
	@RequestMapping(value = "/auth/object-active-add", method = {RequestMethod.GET,RequestMethod.POST})
	public String objectActvieAddAction(HttpSession s,HttpServletRequest req,HttpServletResponse res,PrintWriter out) throws IOException {
		if(!checkView(s, "/auth/object-active")){
    		return accessDenied();
    	}
		
		res.setContentType("txt/html");
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");
		Long urlId = ConvertUtil.toLong(req.getParameter("urlId"));	
		
		Long objectId = ConvertUtil.toLong(req.getParameter("objectId"));
		
		
		Long view = req.getParameter("view") != null ? 1L :0;
		Long insert = req.getParameter("insert") != null ? 1L :0;
		Long update = req.getParameter("update") != null ? 1L :0;
		Long delete = req.getParameter("delete") != null ? 1L :0;
		
		if(objectId != null){
			Role role = roleService.find(objectId);
			
			AuthAcept obj = authAceptService.find(urlId, objectId,loginAuth);
			if(obj == null){
				obj = new AuthAcept();
			}			
			obj.setObjectId(role.getRoleId());
			obj.setObjectName(role.getRoleDescription());
			obj.setUrlId(urlId);			
			obj.setActiveView(view);
			obj.setActiveInsert(insert);
			obj.setActiveUpdate(update);
			obj.setActiveDelete(delete);
			obj.setObjectType(loginAuth.getObjectType());
			obj.setCompanyId(loginAuth.getCompanyId());
			
			if(obj.getId() != null){
				authAceptService.edit(obj);
			}else{
				
				authAceptService.create(obj);
			}
		}else{
			
			out.write("Vai tro khong hop le");
		}
		
				
		out.write("");
		return null;
	}
	@RequestMapping(value = "/auth/object-active-delete", method = {RequestMethod.GET,RequestMethod.POST})
	public String objectActvieDeleteAction(HttpSession s,HttpServletRequest req,HttpServletResponse res,PrintWriter out) throws IOException {
		if(!checkView(s, "/auth/object-active")){
    		return accessDenied();
    	}
		Long id = req.getParameter("id") != null ? Long.parseLong(req.getParameter("id")) : 0L;		
		authAceptService.remove(authAceptService.find(id));		
		return null;
	}
	
	@RequestMapping(value = "/auth/object-ajax", method = {RequestMethod.GET,RequestMethod.POST})
	public String objectAjaxAction(Model model,HttpSession s,HttpServletRequest req,HttpServletResponse res,PrintWriter out) throws IOException {
		if(!checkView(s, "/auth/object-active")){
    		return accessDenied();
    	}
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");		
		String urlId = req.getParameter("urlId");		
		model.addAttribute("urlId", urlId);
		
	    List<AuthAcept> authAcepts = authAceptService.findAll(Long.parseLong(urlId),loginAuth);
	    model.addAttribute("authAcepts", authAcepts);
	    model.addAttribute("rolies", roleService.findAll(loginAuth,null));	
		return "auth/object-ajax";
	}
	
	@RequestMapping(value = "/auth/login-comp-approve", method = {RequestMethod.GET,RequestMethod.POST})
	public String loginCompApproveAction(Model model,HttpSession s,HttpServletRequest req,HttpServletResponse res) throws IOException {
		if(!checkView(s, "/auth/object-active")){
    		return accessDenied();
    	}
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");
		setValueDisplay(model,loginAuth,null,null,null);		
		return "auth/login-comp-approve";
	}
	
	@RequestMapping(value = "/auth/login-emp-approve", method = {RequestMethod.GET,RequestMethod.POST})
	public String loginEmpApproveAction(Model model,HttpSession s,HttpServletRequest req,HttpServletResponse res,PrintWriter out) throws IOException {
		if(!checkView(s, "/auth/object-active")){
    		return accessDenied();
    	}
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");
		if(loginAuth.getObjectType().equals(ObjectType.TYPE_SERVICE.getKey())){
			Long companyId = !ConvertUtil.isEmplty(req.getParameter("companyId")) ? Long.parseLong(req.getParameter("companyId")) : 0L;
			
			List<Auth> empAuths = authService.findByCompanyAll(null,companyId);		
			model.addAttribute("empAuths",  empAuths);		
			return "auth/login-emp-approve";
		}
		return null;
	}
		
	@RequestMapping(value = "/auth/object-status", method = {RequestMethod.GET,RequestMethod.POST})
	public String statusActiveAction(Model model,HttpSession s,HttpServletRequest req,Long accountId,String accountName,Long roleId,Boolean active) throws IOException {
		if(!checkView(s, "/auth/object-active")){
    		return accessDenied();
    	}
		Auth loginAuth = (Auth)s.getAttribute("loginAuth");
		Long authActive = active !=null ? 1L : 0L;
		if(accountId!=null){
			Auth auth = authService.find(accountId);
			
			if(auth.getParentId() == null){
			    List<Auth> list =	authService.findAll(auth.getId(),null,null,null);
			    for(Auth a : list){
			    	a.setActive(authActive);		
					authService.edit(a);
			    }
			}
			auth.setActive(authActive);				
			auth.setRoleId(roleId);		
			authService.edit(auth);
		}
		setValueDisplay(model,loginAuth,roleId,accountName,authActive);
		
		return "auth/login-comp-approve";
	}
	
	@RequestMapping(value = "auth/uploadImage" ,method = {RequestMethod.GET, RequestMethod.POST})
	public String updateImageAction(HttpSession s,HttpServletRequest req,HttpServletResponse res,PrintWriter out){
		String contentImage = UpdateFileUtil.getContentImage(req);
		res.setContentType("txt/html");
		out.write(contentImage);
		out.flush();
		out.close();
        return null;
    }
	
	//---------------
	@RequestMapping(value = "/auth/login", method = {RequestMethod.GET,RequestMethod.POST})
	public String loginAction(Model model,HttpSession s,HttpServletRequest req,HttpServletResponse res,String accountName,String password ) throws IOException {
		String method = "" + req.getMethod();
		if(method.toLowerCase().equals("get")){
			return "auth/login-form";
		} else {
			if(ConvertUtil.isEmplty(accountName) || !FormatUtil.isEmail(accountName)){			
				model.addAttribute("accountName_invalid","Email không hợp lệ");
				return "auth/login-form";
			}
			model.addAttribute("accountName",accountName);
			if(ConvertUtil.isEmplty(password)){			
				model.addAttribute("password_invalid","Mật khâu không hợp lệ");
				return "auth/login-form";
			}
			
			Auth loginAuth = authService.checkLogin(accountName,ConvertUtil.md5Hash(password));
			if(ConvertUtil.isNull(loginAuth)){
				model.addAttribute("accountName_invalid","Thông tin đăng nhập không hợp lệ");
				return "auth/login-form";
			}else{
				if(ConvertUtil.isEqual(loginAuth.getObjectType(), ObjectType.TYPE_SERVICE.getKey())){
					s.setAttribute("urls",  UrlFixed.getUrls());
				}else{
					s.setAttribute("urls",  UrlFixed.getUrls(authAceptService.findByRole(loginAuth.getRoleId())));
				}
				
				s.setAttribute("loginAuth", loginAuth);
				res.sendRedirect("");
			}			
		}
		return null;	
				
	}
	@RequestMapping(value = "/auth/logout")
	public String logoutAction(HttpSession s,HttpServletRequest req,HttpServletResponse res) throws IOException {

		s.invalidate();
		
		return "redirect:login";
	}
	@RequestMapping(value = "/auth/change-password")
	public String changePasswordAction(HttpSession s,HttpServletRequest req,HttpServletResponse res,PrintWriter out) throws IOException {
		res.setContentType("txt/html");
		String mypassword = req.getParameter("mypassword");
		String newpassword = req.getParameter("newpassword");
		String configpassword = req.getParameter("configpassword");	
		if(ConvertUtil.isEqual(newpassword, configpassword) && !ConvertUtil.isEmplty(mypassword)
				&& !ConvertUtil.isEmplty(newpassword) && !ConvertUtil.isEmplty(configpassword)){
			Auth loginAuth = (Auth)s.getAttribute("loginAuth");
			if( ConvertUtil.isEqual(loginAuth.getPassword(), ConvertUtil.md5Hash(mypassword)) ){
				loginAuth.setPassword(ConvertUtil.md5Hash(newpassword));
				authService.edit(loginAuth);
				s.setAttribute("loginAuth", loginAuth);
				out.write("ok");
			}else{
				out.write("Mật khẩu không hợp lệ");
			}
			
		}else{
			
			out.write("Mật khẩu không hợp lệ");
		}	
		return null;
	}
	
	//---------------------------------------------
	protected void setValueDisplay(Model model ,Auth loginAuth,Long roleActive,String accountName ,Long authActive) {
		
		List<Auth> auths = null;
		
		if(loginAuth.getObjectType().equals(ObjectType.TYPE_SERVICE.getKey())){
			auths = authService.findAll(null,roleActive,accountName,authActive);
		}else{
			auths = authService.findAll(loginAuth.getId(),roleActive,accountName,authActive);
		}
				
		model.addAttribute("auths",  auths);		
		model.addAttribute("rolies", roleService.findAll(loginAuth,null));		
		model.addAttribute("roleId", roleActive);
		model.addAttribute("accountName", accountName);
		model.addAttribute("status", authActive);
		
	}

}
